/*
 * Copyright 2007 Agile Plugins Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.agileplugins.monkey;

import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.util.IncorrectOperationException;

import java.util.HashSet;
import java.util.Set;

public class NullCheckIntention extends BaseIntention implements IntentionAction {
    private boolean constructor;

    public NullCheckIntention() {
    }

    public String getText() {
        return constructor ? "Add Null Checks and Fields to Constructor" : "Add Null Checks to Method";
    }

    public boolean isAvailable(Project project, Editor editor, PsiFile psiFile) {
        PsiElement element = getElement(editor, psiFile);
        PsiMethod method = getContainingMethodIfInHeader(element);
        if (method == null) {
            return false;
        }
        constructor = method.isConstructor();
        PsiParameterList parameterList = method.getParameterList();
        PsiParameter[] parameters = parameterList.getParameters();
        PsiCodeBlock body = method.getBody();
        if (body == null) {
            return false;
        }
        PsiStatement[] statements = body.getStatements();
        int sid = 0;
        if (constructor && statements.length > 0) {
            String text = statements[0].getText();
            if (text.startsWith("this(") || text.startsWith("super(")) {
                sid++;
            }
        }
        String nullCheckStatementString = createNullCheckStatement(parameters);
        if (statements.length <= sid || !statements[sid].getText().equals(nullCheckStatementString)) {
            return true;
        }
        return constructor && statements.length < sid + parameters.length;
    }

    private PsiMethod getContainingMethodIfInHeader(PsiElement element) {
        while (element != null && !(element instanceof PsiMethod)) {
            element = element.getParent();
            if (element instanceof PsiCodeBlock) {
                return null;
            }
        }
        return (PsiMethod) element;
    }

    public void invoke(Project project, Editor editor, PsiFile psiFile) throws IncorrectOperationException {
        PsiMethod method = (PsiMethod) getContainingElement(getElement(editor, psiFile), PsiMethod.class);
        PsiManager manager = method.getManager();
        PsiElementFactory elementFactory = manager.getElementFactory();
        PsiCodeBlock body = method.getBody();
        PsiStatement[] statements = body.getStatements();
        PsiElement firstPoint = body.getLBrace();
        for (int i = 0; i < statements.length; i++) {
            PsiStatement statement = statements[i];
            String text = statement.getText();
            if (i == 0 && text.startsWith("this(") || text.startsWith("super(")) {
                firstPoint = statement;
            }
            if (text.startsWith("nullCheck") ||
                    (constructor && statement.getText().matches("this.([^=\\s]+)\\s*=\\s*\\1;"))) {
                statement.delete();
            }
        }
        PsiClass cla = method.getContainingClass();
        PsiField[] fields = cla.getFields();
        Set fieldNames = new HashSet();
        for (int i = 0; i < fields.length; i++) {
            fieldNames.add(fields[i].getName());
        }
        PsiElement lastField = fields.length > 0 ? (PsiElement) fields[fields.length - 1] : cla.getLBrace();
        PsiParameter[] parameters = method.getParameterList().getParameters();
        if (constructor) {
            for (int i = 0; i < parameters.length; i++) {
                String paramName = parameters[i].getName();
                PsiStatement fieldAssignmentStatement = elementFactory.createStatementFromText(
                        "this." + paramName + " = " + paramName + ";", method);
                body.addBefore(fieldAssignmentStatement, body.getRBrace());
                if (!fieldNames.contains(paramName)) {
                    PsiField fieldFromText = elementFactory.createFieldFromText(
                            "private final " + parameters[i].getText() + ";", cla);
                    lastField = cla.addAfter(fieldFromText, lastField);
                }
            }
        }
        String nullCheckStatementString = createNullCheckStatement(parameters);
        if (nullCheckStatementString != null) {
            PsiStatement nullCheckStatement = elementFactory.createStatementFromText(nullCheckStatementString, body);
            body.addAfter(nullCheckStatement, firstPoint);
        }
    }

    private String createNullCheckStatement(PsiParameter[] parameters) {
        int nullCheckParameters = 0;
        for (int i = 0; i < parameters.length; i++) {
            PsiParameter parameter = parameters[i];
            if (!(parameter.getType() instanceof PsiPrimitiveType)) {
                nullCheckParameters++;
            }
        }
        StringBuffer sb = new StringBuffer();
        if (nullCheckParameters > 5) {
            sb.append("nullCheckMany(new Object[]{");
        } else if (nullCheckParameters > 0) {
            sb.append("nullCheck(");
        }
        boolean needComma = false;
        for (int i = 0; i < parameters.length; i++) {
            String paramName = parameters[i].getName();
            if (!(parameters[i].getType() instanceof PsiPrimitiveType)) {
                if (needComma) {
                    sb.append(", ");
                }
                sb.append(paramName);
                needComma = true;
            }

        }
        if (nullCheckParameters > 0) {
            if (nullCheckParameters > 5) {
                sb.append("}");
            }
            sb.append(");");
            return sb.toString();
        }
        return null;
    }
}